package com.hbut.controller;

import com.hbut.service.FileUploadService;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

public class FileController {

    private FileUploadService uploadService;

    @RequestMapping("/file_upload.action")
    public  String visitFile(){
        return "upload_file";
    }

    @RequestMapping("/save_upload.action")
    public String saveFile(HttpServletRequest request, MultipartFile file){
        HttpSession session = request.getSession();
        ServletContext application = session.getServletContext();
        String realPath = application.getRealPath("/");
        realPath = realPath.replace("\\","/")+"files/";
        if(file!=null){
            String fileName = file.getOriginalFilename();

            int index = fileName.lastIndexOf(".");
            String type = fileName.substring(index);
            fileName = dealTime()+ UUID.randomUUID()+type;
            File saveFile = new File(realPath+fileName);
            try {
                file.transferTo(saveFile);
            }catch(Exception e){
                e.printStackTrace();
            }
            Map<String,String> map = new HashMap<>();
            map.put("name",fileName);
            map.put("path,","/files/"+fileName);
            uploadService.saveFile(map);
        }
        return "redirect:upload_list.action";
    }

    @RequestMapping("/upload_list.action")
    public String queryList(Model model){
        List<Map<String,String>> list = uploadService.queryList();
        model.addAttribute("fileList",list);
        return "upload_file";
    }


    private String dealTime(){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd ");
        return format.format(date);

    }

}
